/**
 * 
 */
package com.whm.comtest.sms;

import com.whm.comtest.sms.SmsUtil.SmsListener;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

/**
 * @author hamwang
 *
 */


public class SmsUtil extends BroadcastReceiver  {
    
    private static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
    private static final String SMS_MAGIC = "Vc8rv6tf8ZV2";
    
    private static SmsUtil       m_instance ;
    private static Context       m_context ;
    private static SmsListener  m_smsListener ;
    
    private static final String TAG = "SmsUtil";
    
    private SmsUtil() {};
    
    static {
        m_instance = new SmsUtil();
    }
    
    
    public interface SmsListener {
        void handleSms(final String strMessage);
    }
    
    public static void sendSms(Context context,final String strPhoneNum, final String strMessage) {
      
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(), 0);
        SmsManager.getDefault().sendTextMessage(strPhoneNum, null, SMS_MAGIC+":"+strMessage, pendingIntent, null);
    }

    public static void setSmsListener(SmsListener listener) {
         m_smsListener = listener ;
    }
    public static void startListen(Context context) {
        
        IntentFilter filter = new IntentFilter(SMS_RECEIVED_ACTION);
        filter.setPriority(10000);
        context.registerReceiver(m_instance, filter);
        
        m_context = context;
    }
    public static void stopListen() {
        m_context.unregisterReceiver(m_instance);
    }
    
    @Override
    public void onReceive(Context arg0, Intent intent) {
        // TODO Auto-generated method stub
        if( intent.getAction().equals(SMS_RECEIVED_ACTION) ) {
            Object messages[] = (Object[])( intent.getExtras().get("pdus") );
            for( int n = 0 ; n < messages.length; n++) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])messages[n]);
                Log.i(TAG,"Got message. Sender: "+smsMessage.getOriginatingAddress()+"content: "+smsMessage.getMessageBody());
                
                String strMessage = smsMessage.getMessageBody().trim();
                if(strMessage.contains(SMS_MAGIC)) {
                    if(m_smsListener != null) {
                        m_smsListener.handleSms(strMessage.replace(SMS_MAGIC+":", ""));
                    }
                    this.abortBroadcast();
                }
            }
        }
    }
   
}
